package com.zhou.service.impl;

import com.zhou.configure.PushConfigure;
import com.zhou.dateUtils.LunarCalendarFestivalUtils;
import com.zhou.dto.IdentityInfo;
import com.zhou.dto.Result;
import com.zhou.dto.Weather;
import com.zhou.dto.WeatherYaYa;
import com.zhou.enums.WxMessageType;
import com.zhou.repository.IdentityInfoDataRepository;
import com.zhou.service.OtherInterfaceService;
import com.zhou.service.PushService;
import com.zhou.service.WeatherService;
import com.zhou.utils.MemoryDayUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lcz
 * @desc 推送服务impl
 * @mail lcz_0130@163.com
 * @date 2023/12/28
 */

@Service
@Slf4j
public class PushServiceImpl implements PushService {
    @Autowired
    private JavaMailSender mailSender;
    @Resource
    private WxMpService wxMpService;
    @Resource
    private PushConfigure pushConfigure;
    @Resource
    private WeatherService weatherService;
    @Resource
    private OtherInterfaceService otherInterfaceService;
    @Resource
    private IdentityInfoDataRepository identityInfoDataRepository;
    // 发送邮件的邮箱
    @Value("${spring.mail.username}")
    private String from;
    // 发送邮件的邮箱
    @Value("${spring.mail.toUser}")
    private String toUser;
    /**
     * 推送模板信息
     *
     * @return {@link Result}
     */
    public Result pushTemplate(IdentityInfo identityInfo) {
        Result result = new Result();
        // 构建模板消息
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .templateId(pushConfigure.getTemplateId())
                .build();
        // 计算天数
        long loveDays = MemoryDayUtil.calculationLianAi(pushConfigure.getLoveDate());
        long birthdays = 0;
        if (pushConfigure.isUseLunar()) {
            // 如果使用农历生日
            birthdays = MemoryDayUtil.calculationBirthdayByLunar(pushConfigure.getBirthday());
        } else {
            birthdays = MemoryDayUtil.calculationBirthday(pushConfigure.getBirthday());
        }
        templateMessage.addData(new WxMpTemplateData("loveDays", loveDays + "", "#FF1493"));
        templateMessage.addData(new WxMpTemplateData("birthdays", birthdays + "", "#FFA500"));

        Result weatherResult;

        // 获取天气数据,先判断是否使用丫丫天气接口
        if (StringUtils.isNoneBlank(identityInfo.getLatitude(), identityInfo.getLongitude())) {
            //丫丫天气接口
            Map<String, String> mapYaYa = new HashMap<>();
            mapYaYa.put("city", identityInfo.getLatitude() + "," + identityInfo.getLongitude());
            mapYaYa.put("key", pushConfigure.getYy_weather_ak());
            weatherResult = weatherService.getYaYaWeather(mapYaYa);

        } else {
            //百度天气接口
            Map<String, String> mapBaiDu = new HashMap<>();
            mapBaiDu.put("district_id", identityInfo.getDistrictId());
            mapBaiDu.put("ak", pushConfigure.getBaidu_ak());
            weatherResult = weatherService.getBaiDuWeather(mapBaiDu);
        }

        StringBuilder messageAll = new StringBuilder();
        if (!"200".equals(weatherResult.getCode())) {
            messageAll.append("<br/>");
            messageAll.append(weatherResult.getMessage());
            templateMessage.addData(new WxMpTemplateData("weather", "***", "#00FFFF"));
        } else {
            if (StringUtils.isNoneBlank(identityInfo.getLatitude(), identityInfo.getLongitude())) {
                WeatherYaYa weatherYaYa = (WeatherYaYa) weatherResult.getData();
                // 拿到农历日期
                LunarCalendarFestivalUtils festival = new LunarCalendarFestivalUtils();
                festival.initLunarCalendarInfo(weatherYaYa.getDate());
                templateMessage.addData(new WxMpTemplateData("date", weatherYaYa.getDate(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("lunar", festival.getLunarYear() + "年 " + festival.getLunarMonth() + "月" + festival.getLunarDay(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("festival", festival.getLunarTerm() + " " + festival.getSolarFestival() + " " + festival.getLunarFestival(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("weather", weatherYaYa.getTq(), "#00FFFF"));
                templateMessage.addData(new WxMpTemplateData("low", weatherYaYa.getQw2() + "", "#173177"));
                templateMessage.addData(new WxMpTemplateData("temp", weatherYaYa.getQw() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wc_day", weatherYaYa.getFl() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wd_day", weatherYaYa.getFx() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("high", weatherYaYa.getQw1() + "", "#FF6347"));
                templateMessage.addData(new WxMpTemplateData("city", weatherYaYa.getCityName() + "", "#173177"));
            } else {
                Weather weather = (Weather) weatherResult.getData();
                // 拿到农历日期
                LunarCalendarFestivalUtils festival = new LunarCalendarFestivalUtils();
                festival.initLunarCalendarInfo(weather.getDate());
                templateMessage.addData(new WxMpTemplateData("date", weather.getDate() + "" + weather.getWeek(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("lunar", festival.getLunarYear() + "年 " + festival.getLunarMonth() + "月" + festival.getLunarDay(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("festival", festival.getLunarTerm() + " " + festival.getSolarFestival() + " " + festival.getLunarFestival(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("weather", weather.getText_now(), "#00FFFF"));
                templateMessage.addData(new WxMpTemplateData("low", weather.getLow() + "", "#173177"));
                templateMessage.addData(new WxMpTemplateData("temp", weather.getTemp() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wc_day", weather.getWc_day() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wd_day", weather.getWd_day() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("high", weather.getHigh() + "", "#FF6347"));
                templateMessage.addData(new WxMpTemplateData("city", weather.getCityName() + "", "#173177"));
            }
        }
        // 天行数据接口
        Result rainbowResult = otherInterfaceService.getRainbow();
        if (!"200".equals(rainbowResult.getCode())) {
            messageAll.append("<br/>");
            messageAll.append(rainbowResult.getMessage());
        } else {
            String data = (String) rainbowResult.getData();
            data = data.replaceAll("\r|\n", "");
            templateMessage.addData(new WxMpTemplateData("rainbow", data, "#FF69B4"));
        }
        // 备注
        String remark = "";
        if (loveDays % 365 == 0) {
            remark = "\n今天是恋爱" + (loveDays / 365) + "周年纪念日!";
        }
        if (birthdays == 0) {
            remark = "\n今天是生日,生日快乐呀!";
        }
        if (loveDays % 365 == 0 && birthdays == 0) {
            remark = "\n今天是生日,也是恋爱" + (loveDays / 365) + "周年纪念日!";
        }
        templateMessage.addData(new WxMpTemplateData("remark", remark, "#FF1493"));
        log.info("模板内容：{}", templateMessage.toJson());

        templateMessage.setToUser(identityInfo.getOpenId());
        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            result.setCode("500");
            result.setMessage(messageAll.toString());
            return result;
        }
        result.setCode("200");
        result.setMessage("成功推送" + messageAll);
        return result;
    }

    /**
     * 推送自定义消息
     *
     * @return {@link Result}
     */
    @Override
    public Result pushCustom(String content, String userId) {
        Result result = new Result();
        WxMpKefuMessage wxMpKefuMessage = new WxMpKefuMessage();
        wxMpKefuMessage.setMsgType(WxMessageType.TEXT.getType());
        wxMpKefuMessage.setContent(content);
        wxMpKefuMessage.setToUser(userId);
        try {
            wxMpService.getKefuService().sendKefuMessage(wxMpKefuMessage);
        } catch (WxErrorException e) {
            result.setCode("500");
            result.setMessage(e.getMessage());
            return result;
        }
        sendSimpleMail("自定义消息", content);
        result.setCode("200");
        return result;
    }

    /**
     * 根据经纬度推送天气消息
     *
     * @param requestMap 请求映射
     * @return {@link Result}
     */
    @Override
    public Result pushWeather(Map<String, String> requestMap) {
        log.info("开始推送天气消息");
        Result result = new Result();
        IdentityInfo identityInfo = new IdentityInfo();
        identityInfo.setLatitude(requestMap.get("Location_X"));
        identityInfo.setLongitude(requestMap.get("Location_Y"));
        identityInfo.setAddress(requestMap.get("Label"));

        Map<String, String> personalInformationMap = otherInterfaceService.getWeatherMap(identityInfo);
        String content = "当前位置：" + identityInfo.getAddress() + "\n" +
                "\n" +
                "实时天气：" + personalInformationMap.get("now_temp") + "°C  " + personalInformationMap.get("now_weather") + "\n" +
                "气象：" + personalInformationMap.get("now_wind_dir") + "" + personalInformationMap.get("now_wind_class") + " | 湿度" + personalInformationMap.get("now_rh") + "%\n" +
                "今天：" + personalInformationMap.get("today_weather") + "  " + personalInformationMap.get("today_high") + "/" + personalInformationMap.get("today_low") + "°C\n" +
                "\n" + personalInformationMap.get("poem");
        sendSimpleMail("天气推送", content);
        pushCustom(content, requestMap.get("FromUserName"));
        result.setCode("200");
        result.setMessage("推送成功");
        return result;
    }

    /**
     * 推送新闻消息
     */
    @Override
    public Result pushNews(Map<String, String> requestMap) {
        WxMpKefuMessage wxMpKefuMessage = new WxMpKefuMessage();
        wxMpKefuMessage.setMsgType(WxMessageType.NEWS.getType());
        WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
        //设置点击跳转的链接
        article.setUrl(requestMap.get("url"));
        //设置图片
        article.setPicUrl(requestMap.get("picUrl"));
        //设置描述
        article.setDescription(requestMap.get("description"));
        //设置标题
        article.setTitle(requestMap.get("title"));
        //设置图文消息内容
        wxMpKefuMessage.setArticles(Collections.singletonList(article));
        //设置接收者
        wxMpKefuMessage.setToUser(requestMap.get("openId"));
        try {
            wxMpService.getKefuService().sendKefuMessage(wxMpKefuMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 简单文本邮件
     *
     * @param subject 主题
     * @param content 内容
     */
    public void sendSimpleMail(String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(from);
        //邮件接收人
        message.setTo(toUser);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        mailSender.send(message);
    }
}
